#!/bin/bash
# Automatically deploy shadowsocks
# Time: 20170811

# Check whether the system is centos.
if [ $(cat /etc/redhat-release|awk '{print $1}') = "CentOS" ] ; then
        echo "Congratulations to you!"
else
        echo "Only support CentOS/RedHat!"
        exit 1    
fi

# Install shadowsocks
yum install python-setuptools -y && easy_install pip
pip install shadowsocks

# Create profile directory
if test ! -d /data/vpn/
then
    mkdir -p /data/vpn
else
   echo "Direcroy already exists."
   
   if test -f /data/vpn/shadowsocks.json ; then
       echo "Json profile already exists."
   fi

   if test ! -e data/vpn/ms.sh ; then
       echo "Management scripts already exists." 
   fi
fi
     
#outerIP=`curl -s ip.cn|awk '{print $2}'|awk -F '：' '{print $NF}'`

# Create multiple user profiles
echo '{
    "server":"0.0.0.0",
    "port_password":{
        "50000":"P@&&(^r#leopaocao"
    },
    "timeout":300,
    "method":"rc4-md5",
    "fast_open":false,
    "workers":20
}' > /data/vpn/shadowsocks.json

# Create a startup script
echo '
[Unit]
Description=shadowsocks
After=network.target

[Service]
Type=forking
ExecStart=/data/vpn/ms.sh start
ExecStop=/data/vpn/ms.sh stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
' > /tmp/shadowsocks.service
chmod a+x /tmp/shadowsocks.service

# Create a script file

echo '#!/bin/bash
# shadowsocks start && stop
/usr/bin/python2 /usr/bin/ssserver -c /data/vpn/shadowsocks.json -d $1' > /data/vpn/ms.sh 
chmod a+x /data/vpn/ms.sh

# Add startup script
if [ `cat /etc/redhat-release|awk '{print $3}'|awk -F '.' '{print $1}'` = "6" ] ; then
    echo "/bin/bash /data/vpn/ms.sh start" >> /etc/rc.local
elif [ `cat /etc/redhat-release|awk '{print $4}'|awk -F '.' '{print $1}'` = "7" ] ; then
    /bin/cp /tmp/shadowsocks.service /lib/systemd/system/
    systemctl enable shadowsocks.service
else
    echo "Is this operation system CentOS?"
fi    

echo """
# Management
/bin/bash /data/vpn/ms.sh start
/bin/bash /data/vpn/ms.sh stop

# Add a new user
Add "different_port":"passwd" to the shadowsocks.json.
example:
"port_password":{
        "50000":"woaimalaxiaolongxia",
        "50001":"woaimalaxiaolongxia",
        "50002":"woaimalaxiaolongxia"
 }, 
"""
systemctl start shadowsocks.service
